package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.winning.pmph.composeVo.KaKLFs;
import com.winning.pmph.composeVo.KaKLFsaTI;
import com.winning.pmph.composeVo.KsaKLFsaKUFs;
import com.winning.pmph.composeVo.KsaKLFsaTI;
import com.winning.pmph.entity.*;
import com.winning.pmph.service.*;
import com.winning.pmph.utils.Const;
import com.winning.pmph.utils.KnowledgeEditUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(value = "知识资源管理/素材")
@RestController
@RequestMapping("/pmph/action/knowledgeUnit")
public class KnowledgeUnitCtrl {

    @Resource
    private KnowledgeUnitService service;
    @Resource
    private BookService bookService;
    @Resource
    private KnowledgeLibService knowledgeLibService;
    @Resource
    private TagService tagService;
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private KnowledgeUnitService knowledgeUnitService;
    @Resource
    private KnowledgeUnitParseKnowledgeTaskService knowledgeUnitParseKnowledgeTaskService;
    @Resource
    private KnowledgeUnitParseKnowledgeTaskItemService knowledgeUnitParseKnowledgeTaskItemService;
    @Resource
    private KnowledgeUnitFieldService knowledgeUnitFieldService;

    @GetMapping("selectListByBookId")
    public List<KnowledgeUnit> selectListByBookId(String bookId) {
        return service.lambdaQuery().eq(KnowledgeUnit::getBookId, bookId).list();
    }

    /**
     * 素材库页面
     *
     * @param knowledgeUnit
     * @return
     */
    @ApiOperation(value = "selectPage", notes = "素材库页面列表")
    @GetMapping("selectPage")
    public Page<KnowledgeUnit> selectPage(KnowledgeUnit knowledgeUnit) {
        Page<KnowledgeUnit> page = new Page<>(knowledgeUnit.getCurrentPage(), knowledgeUnit.getPageSize());
        LambdaQueryWrapper<KnowledgeUnit> queryWrapper = Wrappers.lambdaQuery(KnowledgeUnit.class);
        // 知识单元状态, 已入素材库;
        queryWrapper.eq(KnowledgeUnit::getStatus, Const.KNOWLEDGE_UNIT_STATUS_MATERIAL);
        // 已关联知识, 表明已建子任务, 过滤;
        queryWrapper.eq(knowledgeUnit.isFilterExistKnowledgeFlag(), KnowledgeUnit::getKnowledgeId, StringUtils.EMPTY);
        // 知识单元名称过滤;
        queryWrapper.like(StringUtils.isNotEmpty(knowledgeUnit.getName()), KnowledgeUnit::getName, knowledgeUnit.getName());
        // 根据图书名称, isbn过滤;
        if (StringUtils.isNotEmpty(knowledgeUnit.getBookName())
                || StringUtils.isNotEmpty(knowledgeUnit.getBookIsbn())) {
            List<String> bookIds = bookService.lambdaQuery().select(Book::getId)
                    .eq(Book::getMarkedStatus, Const.BOOK_MARKED_STATUS_DONE)
                    .eq(StringUtils.isNotEmpty(knowledgeUnit.getBookIsbn()), Book::getIsbn, knowledgeUnit.getBookIsbn())
                    .like(StringUtils.isNotEmpty(knowledgeUnit.getBookName()), Book::getName, knowledgeUnit.getBookName())
                    .list().stream().map(Book::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(bookIds)) {
                return page;
            }
            queryWrapper.in(KnowledgeUnit::getBookId, bookIds);
        }
        // 类别;
        queryWrapper.eq(StringUtils.isNotEmpty(knowledgeUnit.getCategory()), KnowledgeUnit::getCategory, knowledgeUnit.getCategory());
        // 类别不能为空;
        queryWrapper.ne(KnowledgeUnit::getCategory, StringUtils.EMPTY);
        // 分类标签过滤;
        if (StringUtils.isNotEmpty(knowledgeUnit.getTagVo())) {
            queryWrapper.like(KnowledgeUnit::getTag, knowledgeUnit.getTagVo());
        }
        // 自由标签, 前端传递Vo
        queryWrapper.like(StringUtils.isNotEmpty(knowledgeUnit.getCustomTagVo()), KnowledgeUnit::getCustomTag, knowledgeUnit.getCustomTagVo());
        // 入库时间
        if (CollectionUtils.isNotEmpty(knowledgeUnit.getSubmitMaterialTimeRange())) {
            queryWrapper.gt(KnowledgeUnit::getSubmitMaterialTime, knowledgeUnit.getSubmitMaterialTimeRange().get(0))
                    .lt(KnowledgeUnit::getSubmitMaterialTime, knowledgeUnit.getSubmitMaterialTimeRange().get(1));
        }
        // 入库时间排序;
        queryWrapper.orderByDesc(KnowledgeUnit::getSubmitMaterialTime).orderByAsc(KnowledgeUnit::getId);
        page = service.page(page, queryWrapper);
        // 知识单元转vo, 会用到知识库和分类标签表, mapper层加缓存, 单条转换和集合转换性能相近;
        page.getRecords().forEach(this::parseVo);
        return page;
    }

    /**
     * 标注页面;
     */
    @ApiOperation(value = "selectList", notes = "标注页面列表")
    @GetMapping("selectList")
    public List<KnowledgeUnit> selectList(KnowledgeUnit knowledgeUnit) {
        List<KnowledgeUnit> knowledgeUnitList = service
                .lambdaQuery()
                .eq(KnowledgeUnit::getBookId, knowledgeUnit.getBookId())
                .eq(KnowledgeUnit::getStatus, Const.KNOWLEDGE_UNIT_STATUS_RELEASE)
                .list();
        // 知识单元转vo, 会用到知识库和分类标签表, mapper层加缓存, 单条转换和集合转换性能相近;
        knowledgeUnitList.forEach(this::parseVo);
        return knowledgeUnitList;
    }

    @ApiOperation(value = "insertList", notes = "知识单元保存接口")
    @PostMapping("insertList")
    public void insertList(@RequestBody List<KnowledgeUnit> knowledgeUnitList) {
        for (KnowledgeUnit knowledgeUnit : knowledgeUnitList) {
            setKnowledgeUnitContent(knowledgeUnit);
        }
        service.saveBatch(knowledgeUnitList);
    }

    @ApiOperation(value = "insertListAndReleased", notes = "知识单元保存并标注接口")
    @PostMapping("insertListAndReleased")
    public List<KnowledgeUnit> insertListAndReleased(@RequestBody List<KnowledgeUnit> knowledgeUnitList, String bookId, String markedRate) {
        for (KnowledgeUnit knowledgeUnit : knowledgeUnitList) {
            setKnowledgeUnitContent(knowledgeUnit);
        }
        List<KnowledgeUnit> updatedKnowledgeUnitList = service.insertListAndReleased(knowledgeUnitList, bookId, markedRate);
        updatedKnowledgeUnitList.forEach(this::parseVo);
        return updatedKnowledgeUnitList;
    }

    private void setKnowledgeUnitContent(KnowledgeUnit knowledgeUnit) {
        if (StringUtils.isEmpty(knowledgeUnit.getContent())) {
            String bookArticleContent = bookService.getKnowledgeUnitContentByCatalogId(knowledgeUnit.getBookCatalogItemId());
            knowledgeUnit.setContent(bookArticleContent);
        }
    }

    @ApiOperation(value = "updateById", notes = "知识单元修改接口")
    @PostMapping("/updateById")
    public void updateById(@RequestBody KnowledgeUnit knowledgeUnit) {
        service.updateById(knowledgeUnit);
    }

    @ApiOperation(value = "deleteById", notes = "知识单元删除接口")
    @PostMapping("/deleteById")
    public void deleteById(@RequestBody KnowledgeUnit knowledgeUnit) {
        service.removeById(knowledgeUnit.getId());
    }

    @ApiOperation(value = "deleteList", notes = "知识单元批量删除接口")
    @PostMapping("/deleteList")
    public void deleteList(@RequestBody List<String> knowledgeUnitIdList) {
        service.removeByIds(knowledgeUnitIdList);
    }

    /**
     * 根据绑定图书目录ID, 获取知识条目内容
     */
    @ApiOperation(value = "selectContentByCatalogId", notes = "根据绑定图书目录ID, 获取知识条目内容")
    @GetMapping("selectContentByCatalogId")
    public BookArticle  selectContentByCatalogId(String bookCatalogItemId) {
        String bookArticleContent = bookService.getKnowledgeUnitContentByCatalogId(bookCatalogItemId);
        BookArticle bookArticle = new BookArticle();
        bookArticle.setUnitContent(bookArticleContent);
        return bookArticle;
    }

    @ApiOperation(value = "saveMark", notes = "保存标记的知识单元")
    @PostMapping("saveMark")
    public List<KnowledgeUnit> saveMark(@RequestBody List<KnowledgeUnit> knowledgeUnitList) {
        service.updateBatchById(knowledgeUnitList);
        knowledgeUnitList.forEach(this::parseVo);
        return knowledgeUnitList;
    }

    private void parseVo(KnowledgeUnit knowledgeUnit) {
        // 类别;
        if (StringUtils.isNotEmpty(knowledgeUnit.getCategory())) {
            knowledgeUnit.setCategoryVo(knowledgeLibService.getById(knowledgeUnit.getCategory()).getName());
        }
        // 分类;
        if (CollectionUtils.isNotEmpty(knowledgeUnit.getTag().values())) {
            Map<String, Tag> tagMap = tagService.selectMap(null);
            String tagVo = "";
            for (String topTagId : knowledgeUnit.getTag().keySet()) {
                JSONArray fieldValue = knowledgeUnit.getTag().getJSONArray(topTagId);
                // tagVo 如果某一项没有值就不再展示;
                if (CollectionUtils.isNotEmpty(fieldValue)) {
                    tagVo += tagMap.get(topTagId).getName() + ": ";
                    // 值为二维数组, 只展示最后一级标签;
                    for (int i = 0; i < fieldValue.size(); i++) {
                        JSONArray innerArray = fieldValue.getJSONArray(i);
                        String leafTagId = innerArray.getString(innerArray.size() - 1);
                        tagVo += tagMap.get(leafTagId).getName() + ", ";
                    }
                    tagVo += "\n";
                }
            }
            knowledgeUnit.setTagVo(tagVo);
        }
        // 自由标签;
        if (CollectionUtils.isNotEmpty(knowledgeUnit.getCustomTag())) {
            String customTagVo = knowledgeUnit.getCustomTag().toJavaList(String.class).stream().collect(Collectors.joining("; "));
            knowledgeUnit.setCustomTagVo(customTagVo);
        }
        // 图书信息;
        Book book = bookService.getById(knowledgeUnit.getBookId());
        if (Objects.nonNull(book)) {
            knowledgeUnit.setBookName(book.getName());
            knowledgeUnit.setBookIsbn(book.getIsbn());
        }
    }

    @ApiOperation(value = "parse2Knowledge", notes = "跳转到单条页面")
    @PostMapping("parse2Knowledge")
    public KaKLFs parse2Knowledge(@RequestBody KnowledgeUnit knowledgeUnit) {
        List<KnowledgeLibField> knowledgeLibFieldList = knowledgeLibService.getKnowledgeLibFieldList(knowledgeUnit.getCategory());
        Knowledge knowledge = prepareKnowledgeAndUnitFieldMap(knowledgeUnit);
        // 根据知识库字段集合 synonym, 填充知识属性knowledgeFieldList;
        populateKnowledgeUnitFieldList(knowledge, knowledgeLibFieldList);
        knowledgeUnitService.prepareKnowledge(knowledge);
        knowledge.getKnowledgeFieldList().forEach(KnowledgeEditUtil::setFieldValue);
        return new KaKLFs(knowledge, knowledgeLibFieldList);
    }

    private void populateKnowledgeUnitFieldList(Knowledge knowledge, List<KnowledgeLibField> knowledgeLibFieldList) {
        for (KnowledgeUnitField knowledgeUnitField : knowledge.getKnowledgeUnitFieldList()) {
            String name = knowledgeUnitField.getName();
            Optional<KnowledgeLibField> knowledgeLibFieldOptional = knowledgeLibFieldList.stream()
                    .filter(klf -> klf.getKind() == KnowledgeLibField.FIELD_KIND_RICHEDITOR)
                    .filter(klf -> StringUtils.equals(klf.getName(), name) || klf.getSynonym().contains(name)).findAny();
            if (knowledgeLibFieldOptional.isPresent()) {
                knowledgeUnitField.setKnowledgeLibFieldIdDefault(knowledgeLibFieldOptional.get().getId());
                knowledgeUnitField.setKnowledgeLibFieldNameDefault(knowledgeLibFieldOptional.get().getName());
            }
        }
    }

    @ApiOperation(value = "parse2KnowledgeList", notes = "跳转到批量页面")
    @PostMapping("parse2KnowledgeList")
    public KsaKLFsaKUFs parse2KnowledgeList(@RequestBody List<KnowledgeUnit> knowledgeUnitList) {
        List<KnowledgeLibField> knowledgeLibFieldList = knowledgeLibService.getKnowledgeLibFieldList(knowledgeUnitList.get(0).getCategory());
        List<Knowledge> knowledgeList = knowledgeUnitList.stream()
                .map(this::prepareKnowledgeAndUnitFieldMap)
                .peek(knowledge -> populateKnowledgeUnitFieldList(knowledge, knowledgeLibFieldList))
                .collect(Collectors.toList());
        Map<String, Long> kuf2countMap = knowledgeList.stream()
                .flatMap(item -> item.getKnowledgeUnitFieldList().stream().map(KnowledgeUnitField::getName))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<KnowledgeUnitField> multiKnowledgeUnitFieldList = prepareKnowledgeUnitFieldList(
                knowledgeLibFieldList.stream()
                        .filter(item -> item.getKind() == KnowledgeLibField.FIELD_KIND_RICHEDITOR)
                        .collect(Collectors.toList()), kuf2countMap);
        return new KsaKLFsaKUFs(knowledgeList, knowledgeLibFieldList, multiKnowledgeUnitFieldList);
    }

    @NotNull
    public Knowledge prepareKnowledgeAndUnitFieldMap(KnowledgeUnit knowledgeUnit) {
        Knowledge knowledge = knowledgeService.getKnowledgeAndFieldById(knowledgeUnit.getKnowledgeId());
        if (Objects.isNull(knowledge)) {
            knowledge = knowledgeService.createKnowledgeByLibId(knowledgeUnit.getCategory());
            // 第一个字段都是知识名称;
            knowledge.setName(knowledgeUnit.getName());
            knowledge.getKnowledgeFieldList().get(0).setProperty(knowledgeUnit.getName());
        }
        knowledge.getKnowledgeFieldList().stream().forEach(item -> item.setSynonym(new JSONArray()));
        knowledge.setKnowledgeUnitId(knowledgeUnit.getId());
        knowledge.setKnowledgeUnitName(knowledgeUnit.getName());
        // 知识单元content 按照下一级标签分段切割;
        knowledgeUnitService.splitKnowledgeUnit(knowledgeUnit);
        // 设置tag类型;
        setKnowledgeFieldTag(knowledgeUnit, knowledge);
        // 字段最后添加自由标签;
        if (CollectionUtils.isNotEmpty(knowledgeUnit.getCustomTag())) {
            KnowledgeUnitField knowledgeUnitField = new KnowledgeUnitField();
            knowledgeUnitField.setKnowledgeUnitId(knowledgeUnit.getId());
            knowledgeUnitField.setName(Const.KNOWLEDGE_UNIT_CUSTOM_TAG_KEY);
            knowledgeUnitField.setContent(knowledgeUnit.getCustomTag().toJSONString());
            knowledgeUnit.getKnowledgeUnitFieldList().add(knowledgeUnitField);
        }
        // 设置默认自由标签(默认匹配第一个多值字段);
//        setCustomTagDefault(knowledgeUnit, knowledge);
        knowledge.setKnowledgeUnitFieldList(knowledgeUnit.getKnowledgeUnitFieldList());
        return knowledge;
    }

    @NotNull
    private List<KnowledgeUnitField> prepareKnowledgeUnitFieldList(List<KnowledgeLibField> knowledgeLibFieldList, Map<String, Long> kuf2countMap) {
        List<KnowledgeUnitField> knowledgeUnitFieldList = Lists.newArrayList();
        for (String key : kuf2countMap.keySet()) {
            KnowledgeUnitField knowledgeUnitField = new KnowledgeUnitField();
            knowledgeUnitField.setName(key);

            Optional<KnowledgeLibField> knowledgeFieldOptional = knowledgeLibFieldList.stream()
                    .filter(item -> StringUtils.equals(item.getName(), key))
                    .findFirst();
            if (!knowledgeFieldOptional.isPresent()) {
                knowledgeFieldOptional = knowledgeLibFieldList.stream()
                        .filter(item -> item.getSynonym().contains(key))
                        .findFirst();
            }
            if (knowledgeFieldOptional.isPresent()) {
                knowledgeUnitField.setKnowledgeLibFieldIdDefault(knowledgeFieldOptional.get().getId());
                knowledgeUnitField.setKnowledgeLibFieldNameDefault(knowledgeFieldOptional.get().getName());
            }
            knowledgeUnitField.setCount(kuf2countMap.get(key).intValue());
            knowledgeUnitFieldList.add(knowledgeUnitField);
        }
        // 按照 count 倒序排序;
        knowledgeUnitFieldList.sort(Comparator.comparingInt(KnowledgeUnitField::getCount).reversed());
        return knowledgeUnitFieldList;
    }

    private void setKnowledgeFieldTag(KnowledgeUnit knowledgeUnit, Knowledge knowledge) {
        // 分类标签赋值;
        for (KnowledgeField knowledgeField : knowledge.getKnowledgeFieldList()) {
            if (knowledgeField.getKind() == KnowledgeLibField.FIELD_KIND_REFERENCE) {
                String topTag = knowledgeField.getKindValue();
                JSONArray tagValue = ObjectUtils.defaultIfNull(knowledgeUnit.getTag().getJSONArray(topTag), new JSONArray());
                if (CollectionUtils.isEmpty(JSON.parseArray(knowledgeField.getProperty()))) {
                    knowledgeField.setProperty(tagValue.toJSONString());
                }
            }
        }
    }

    private void setCustomTagDefault(KnowledgeUnit knowledgeUnit, Knowledge knowledge) {
        // 分类标签赋值;
        if (CollectionUtils.isEmpty(knowledgeUnit.getCustomTag())) {
            return;
        }
        Optional<KnowledgeField> multiInputFieldOptional = knowledge.getKnowledgeFieldList().stream()
                .filter(item -> item.getKind() == KnowledgeLibField.FIELD_KIND_MULTI_VALUE_INPUT)
                .findFirst();
        if (multiInputFieldOptional.isPresent()) {
            multiInputFieldOptional.get().setProperty(knowledgeUnit.getCustomTag().toJSONString());
            Optional<KnowledgeUnitField> customTagFieldOptional = knowledgeUnit.getKnowledgeUnitFieldList().stream()
                    .filter(item -> StringUtils.equals(item.getName(), Const.KNOWLEDGE_UNIT_CUSTOM_TAG_KEY))
                    .findFirst();
            if (customTagFieldOptional.isPresent()) {
                customTagFieldOptional.get().setKnowledgeLibFieldId(multiInputFieldOptional.get().getKnowledgeLibId());
                customTagFieldOptional.get().setKnowledgeLibFieldName(multiInputFieldOptional.get().getName());
            }
        }
    }

    @ApiOperation(value = "insertKnowledge", notes = "跳转到单条页面保存接口")
    @PostMapping("insertKnowledge")
    public void insertKnowledge(@RequestBody KaKLFsaTI param) {
        Knowledge knowledge = param.getKnowledge();
        List<KnowledgeLibField> knowledgeLibFieldList = param.getKnowledgeLibFieldList();
        TaskItem taskItem = param.getTaskItem();
        knowledgeUnitService.insertKnowledge(knowledge, knowledgeLibFieldList, taskItem);
    }

    @ApiOperation(value = "insertKnowledgeList", notes = "跳转到批量页面保存接口")
    @PostMapping("insertKnowledgeList")
    public void insertKnowledgeList(@RequestBody KsaKLFsaTI param) {
        List<Knowledge> knowledgeList = param.getKnowledgeList();
        List<KnowledgeLibField> knowledgeLibFieldList = param.getKnowledgeLibFieldList();
        TaskItem taskItem = param.getTaskItem();
        // 重置知识字段内容, 再组装知识字段内容;
        knowledgeList.forEach(this::resetRichEditorKnowledgeFieldList);
        knowledgeUnitService.insertKnowledgeList(knowledgeList, knowledgeLibFieldList, taskItem);
    }

    @ApiOperation(value = "saveEditingTask", notes = "暂存页面接口")
    @PostMapping("saveEditingTask") // 暂存;
    public void saveEditingTask(@RequestBody KsaKLFsaTI param) {
        List<Knowledge> knowledgeList = param.getKnowledgeList();
        List<KnowledgeLibField> knowledgeLibFieldList = param.getKnowledgeLibFieldList();
        TaskItem taskItem = param.getTaskItem();
        knowledgeUnitService.saveEditingTask(knowledgeList, knowledgeLibFieldList, taskItem);
    }

    @ApiOperation(value = "editTask", notes = "编辑暂存页面接口")
    @GetMapping("editTask")
    public KsaKLFsaKUFs editTask(String taskId) {
        // 根据taskId, 查找子任务knowledgeUnit集合;
        List<KnowledgeUnitParseKnowledgeTaskItem> taskItemList = knowledgeUnitParseKnowledgeTaskItemService.selectByTaskId(taskId);
        List<String> idList = taskItemList.stream()
                .map(KnowledgeUnitParseKnowledgeTaskItem::getKnowledgeUnitId)
                .distinct().collect(Collectors.toList());
        List<KnowledgeUnit> knowledgeUnitList = knowledgeUnitService.lambdaQuery().in(KnowledgeUnit::getId, idList).list();
        KsaKLFsaKUFs result = parse2KnowledgeList(knowledgeUnitList);
        // 替换 knowledgeUnitFieldList;
        List<KnowledgeUnitField> knowledgeUnitFieldList = knowledgeUnitFieldService.lambdaQuery().eq(KnowledgeUnitField::getKnowledgeUnitParseKnowledgeTaskId, taskId).list();
        List<Knowledge> knowledgeList = result.getKnowledgeList();
        Map<String, List<KnowledgeUnitField>> listMap = knowledgeUnitFieldList.stream().collect(Collectors.groupingBy(KnowledgeUnitField::getKnowledgeUnitId));
        knowledgeList.forEach(item -> item.setKnowledgeUnitFieldList(listMap.get(item.getKnowledgeUnitId())));
        Map<String, List<KnowledgeUnitField>> name2ListMap = knowledgeUnitFieldList.stream().collect(Collectors.groupingBy(KnowledgeUnitField::getName));
        List<KnowledgeUnitField> multiKnowledgeUnitFieldList = Lists.newArrayList();
        for (String name : name2ListMap.keySet()) {
            KnowledgeUnitField knowledgeUnitField = new KnowledgeUnitField();
            knowledgeUnitField.setName(name);
            knowledgeUnitField.setCount(name2ListMap.get(name).size());
            Optional<KnowledgeUnitField> knowledgeUnitFieldOptional = name2ListMap.get(name).stream().filter(item -> StringUtils.isNotEmpty(item.getKnowledgeLibFieldIdDefault())).findFirst();
            if (knowledgeUnitFieldOptional.isPresent()) {
                knowledgeUnitField.setKnowledgeLibFieldIdDefault(knowledgeUnitFieldOptional.get().getKnowledgeLibFieldIdDefault());
                knowledgeUnitField.setKnowledgeLibFieldNameDefault(knowledgeUnitFieldOptional.get().getKnowledgeLibFieldNameDefault());
            }
            multiKnowledgeUnitFieldList.add(knowledgeUnitField);
        }
        multiKnowledgeUnitFieldList = multiKnowledgeUnitFieldList.stream().sorted(Comparator.comparingInt(KnowledgeUnitField::getCount).reversed()).collect(Collectors.toList());
        result.setKnowledgeUnitFieldList(multiKnowledgeUnitFieldList);
        result.setKnowledgeList(knowledgeList);
        return result;
    }

    @ApiOperation(value = "deleteTask", notes = "删除任务接口")
    @GetMapping("deleteTask")
    public void deleteTask(String taskId) {
        knowledgeUnitService.deleteTask(taskId);
    }

    @ApiOperation(value = "selectKnowledgeFieldByUnitFieldList", notes = "素材库匹配字段接口")
    @PostMapping("selectKnowledgeFieldByUnitFieldList")
    public Knowledge selectKnowledgeFieldByUnitFieldList(@RequestBody Knowledge knowledge) {
        resetRichEditorKnowledgeFieldList(knowledge);
        knowledgeUnitService.prepareKnowledge(knowledge);
        knowledge.getKnowledgeFieldList().forEach(KnowledgeEditUtil::setFieldValue);
        return knowledge;
    }

    private void resetRichEditorKnowledgeFieldList(Knowledge knowledge) {
        List<KnowledgeField> knowledgeFieldListOri = knowledge.getKnowledgeFieldList();
        knowledgeService.resetKnowledgeFieldList(knowledge);
        // tag类型 不变;
        for (int i = 0; i < knowledge.getKnowledgeFieldList().size(); i++) {
            KnowledgeField knowledgeField = knowledge.getKnowledgeFieldList().get(i);
            if (KnowledgeLibField.FIELD_KIND_REFERENCE == knowledgeField.getKind()) {
                Optional<KnowledgeField> knowledgeFieldOriOptional = knowledgeFieldListOri.stream()
                        .filter(item -> StringUtils.equals(item.getKnowledgeLibFieldId(), knowledgeField.getKnowledgeLibFieldId()))
                        .findFirst();
                if (knowledgeFieldOriOptional.isPresent()) {
                    knowledge.getKnowledgeFieldList().set(i, knowledgeFieldOriOptional.get());
                }
            }
        }
    }

    @ApiOperation(value = "selectHistoryPage", notes = "展示历史列表")
    @GetMapping("selectHistoryPage")
    public Page selectHistoryPage(KnowledgeUnitParseKnowledgeTask task) {
        return knowledgeUnitParseKnowledgeTaskService.selectHistoryPage(task);
    }

    @ApiOperation(value = "selectItemHistory", notes = "展示子任务历史列表")
    @GetMapping("selectItemHistory")
    public List<KnowledgeUnitParseKnowledgeTaskItem> selectItemHistory(String taskId) {
        return knowledgeUnitParseKnowledgeTaskItemService.selectByTaskId(taskId);
    }

    @ApiOperation(value = "selectTaskItemDetail", notes = "展示子任务详情")
    @GetMapping("selectTaskItemDetail")
    public KaKLFs selectTaskItemDetail(String taskId, String taskItemId) {
        KnowledgeUnitParseKnowledgeTaskItem knowledgeUnitParseKnowledgeTaskItem = null;
        if (StringUtils.isNotEmpty(taskItemId)) {
            knowledgeUnitParseKnowledgeTaskItem = knowledgeUnitParseKnowledgeTaskItemService.getById(taskItemId);
        } else {
            knowledgeUnitParseKnowledgeTaskItem = knowledgeUnitParseKnowledgeTaskItemService.singleSelectByTaskId(taskId);
        }
        KnowledgeUnit knowledgeUnit = knowledgeUnitService.getById(knowledgeUnitParseKnowledgeTaskItem.getKnowledgeUnitId());
        KaKLFs result = parse2Knowledge(knowledgeUnit);
        List<KnowledgeUnitField> knowledgeUnitFieldList = knowledgeUnitFieldService.lambdaQuery()
                .eq(KnowledgeUnitField::getKnowledgeUnitParseKnowledgeTaskId, taskId)
                .eq(KnowledgeUnitField::getKnowledgeUnitId, knowledgeUnit.getId()).list();
        Knowledge knowledge = result.getKnowledge();
        // 知识单元字段过滤;
        knowledge.setKnowledgeUnitFieldList(knowledgeUnitFieldList);
        knowledge.getKnowledgeFieldList().forEach(KnowledgeEditUtil::setFieldValue);
        result.setKnowledge(knowledge);
        return result;
    }
}
